import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:village_android/component/loading_Dialog.dart';
import 'package:village_android/config/contants.dart';
import 'package:village_android/utils/common_utils.dart';

class BaseUrl{
  // 配置默认请求地址
  static const String url = 'http://beitingapp.sourcedesign.cn';
//  static const String url = 'http://192.168.220.1:8081';
}

class HttpUtils{


  // 上传图片
  static Future uploadImg(imgfile) async{
    String path = imgfile.path;
    var name = path.substring(path.lastIndexOf("/") + 1, path.length);
    FormData formData = new FormData.from({
      "file": new UploadFileInfo(new File(path), name)
    });

  }

  static void get(
      String url,
      {
        Map<String, dynamic> data,
        Map<String, dynamic> headers,
        Function success,
        Function error,
        BuildContext context,

      }
      ) async {

    // 数据拼接
    var userId = CommonUtils.getUserId();
    if(userId!=null && !data.containsKey("userId")) {
      Map<String, dynamic> userIdMap = new Map();
      userIdMap[K_USER_ID]=  userId;
      data.addAll(userIdMap);
    }
//    var username = CommonUtils.getUsername();
//    if(username!=null) {
//      Map<String, dynamic> userNameMap = new Map();
//      userNameMap[K_USER_NAME]=  username;
//      data.addAll(userNameMap);
//    }
    if(data != null && data.isNotEmpty){

      StringBuffer options= new StringBuffer('?');
      data.forEach((key, value){
        options.write('${key}=${value}&');
      });
      String optionsStr = options.toString();
      optionsStr = optionsStr.substring(0, optionsStr.length - 1);
      url += optionsStr;
    }

    // 发送get请求
    await _sendRequest(
        url,
        'get',
        success,
        headers: headers,
        error: error,
      context: context,
    );
  }

  static void post(
      String url,
      {
        Map<String, dynamic> data,
        Map<String, dynamic> headers,
        Function success,
        Function error,
        BuildContext context,

      }
      ) async {

    // 数据拼接
    var userId = CommonUtils.getUserId();
    if(userId!=null && !data.containsKey("userId")) {
      Map<String, dynamic> userIdMap = new Map();
      userIdMap[K_USER_ID]=  userId;
      data.addAll(userIdMap);
    }
    var username = CommonUtils.getUsername();
    if(username!=null) {
      Map<String, dynamic> userNameMap = new Map();
      userNameMap[K_USER_NAME]=  username;
      data.addAll(userNameMap);
    }

    // 发送post请求
    _sendRequest(
        url,
        'post',
        success,
        data: data,
        headers: headers,
        error: error,
        context: context
    );
  }
  static void postForm(
      String url,
      {
        BuildContext context,
        FormData formData,
        Map<String, dynamic> headers,
        Function success,
        Function error
      }
      ) async {

    // 数据拼接
    var userId = CommonUtils.getUserId();
    if(userId!=null) {
      Map<String, dynamic> userIdMap = new Map();
      userIdMap[K_USER_ID]=  userId;
      formData.addAll(userIdMap);
    }

    var username = CommonUtils.getUsername();
    if(username!=null) {
      Map<String, dynamic> userNameMap = new Map();
      userNameMap[K_USER_NAME]=  username;
      formData.addAll(userNameMap);
    }



    // 发送post请求
    _sendRequest(
        url,
        'post',
        success,
        formData: formData,
        headers: headers,
        error: error,
      context: context,
    );
  }

  // 请求处理
  static Future _sendRequest(
      String url,
      String method,
      Function success,
      {
        Map<String, dynamic> data,
        FormData formData,
        Map<String, dynamic> headers,
        Function error,
        BuildContext context,
      }
      ) async {
    int _code;
    String _msg;
    var _backData;

    // 检测请求地址是否是完整地址
    if(!url.startsWith('http')){
      url = BaseUrl.url + url;
    }

    try{
      Map<String, dynamic> dataMap = data == null ? new Map() : data;
      Map<String, dynamic> headersMap = headers == null ? new Map() : headers;

      // 配置dio请求信息
      Response response;
      Dio dio = new Dio();
      dio.options.connectTimeout = 10000;        // 服务器链接超时，毫秒
      dio.options.receiveTimeout = 3000;         // 响应流上前后两次接受到数据的间隔，毫秒
      dio.options.headers.addAll(headersMap);    // 添加headers,如需设置统一的headers信息也可在此添加

      if(context!=null) {
        showDialog(
            context: context,
            barrierDismissible: false,
            builder: (BuildContext context) {
              return new LoadingDialog(
                text: "处理中…",
              );
            });
      }

      if(method == 'get'){
        response = await dio.get(url);
      }else{
        response = await dio.post(url,data: formData !=null ? formData :dataMap);
      }


      if(response.statusCode != 200){
        _msg = '网络请求错误,状态码:' + response.statusCode.toString();
        _handError(error, _msg);
        return;
      }

      // 返回结果处理
      Map<String, dynamic> resCallbackMap = response.data;
      _code = resCallbackMap['code'];
      _msg = resCallbackMap['msg'];
      _backData = resCallbackMap['data'];

      if(success != null){
        if(_code == 0 || _code == 200){
          success(_backData);
        }else{
          var message = '数据请求错误';
          if(response!=null){
            message = response.data["message"];
          }
          _handError(error, message);
        }
      }

    }catch(exception){

      var message = '数据请求错误';
      DioError dioError = exception as DioError;
      if(dioError.response!=null){
        message = dioError.response.data["message"];
      }
       _handError(error, message);
    }finally{
      if(context!=null) {
        Navigator.pop(context);
      }
    }
  }

  // 返回错误信息
  static Future _handError(Function errorCallback,String errorMsg){
    if(errorCallback != null){
      errorCallback(errorMsg);
    }
  }
}